//index.js
// 注意不要将map放在page构造器内
// 不同天气对应不同图片，用于加载背景
const weatherMap = {
  '晴': 'sunny',
  '多云': 'cloudy',
  '阴': 'overcast',
  '小雨': 'lightrain',
  '大雨': 'heavyrain',
  '阵雨': 'shower',
  '雪': 'snow',
  '雨夹雪': 'sleet'
}
var city = ""
// 不同天气显示不同状态栏颜色
const weatherColorMap = {
  'sunny': '#4AAFFE',
  'cloudy': '#313495',
  'overcast': '#4684A2',
  'lightrain': '#A6DBE8',
  'heavyrain': '#E8DA76',
  'shower': '#5E5C58',
  'snow': '#40B9B3',
  'sleet': '#B7C0C0'
}

// 权限三种状态
const UNPROMPTED = 0
const UNAUTHORIZED = 1
const AUTHORIZED = 2

// 引入腾讯位置服务SDK核心类
const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nowTemp: '', // 当前温度
    nowWeather: '', // 当前天气
    dressIndex: '', // 穿衣指数
    exerciseIndex: '', // 锻炼指数
    washIndex: '', // 洗车指数
    travelIndex: '', // 出行指数
    todayDate: '', // 今天时间
    todayTempScop: '', // 今天的温度范围
    weatherImage: 'overcast', // 背景图片名
    futureData: '', // 一周天气缓存
    location: '成都市', // 位置
    locationAuthType: UNPROMPTED, //默认位置授权状态
    hiddenTest:'ture',
    hiddenmodalput: true,
    cityName: ''
  },

  onLoad: function (options) {
    wx.getSetting({
      success: res => {
        let auth = res.authSetting['scope.userLocation']
        this.setData({
          locationAuthType: auth ? AUTHORIZED : (auth === false ? UNAUTHORIZED : UNPROMPTED)
        })

        if (auth) {
          this.getLocation()
        }
        this.getWeatherData()
      }
    })

    // 实例化API核心类
    this.qqmapsdk = new QQMapWX({
      key: '36ZBZ-74IWX-ZYP4A-7VCZE-DZAFV-5AFZQ'
    })
  },
  onShow:function(){
    app.theCity = location
  },


  getWeatherData(callback) {
    wx.request({
      url: 'https://v.juhe.cn/weather/index',
      data: {
        format: 2,
        cityname: app.globalData.city,
        key: 'c348a885dbbf7e2a2d50303b0fa869b0'
      },
      success: res => {
        this.getNow(res)
        this.getIndex(res)
        this.getToday(res)
        app.globalData.futureData = JSON.stringify(res.data.result.future)
       
      },
      complete: () => {
        callback && callback()
      }
    })
  },
  /**
   * 解析获得当前天气数据
   */
  getNow(res) {
    let temp = res.data.result.sk.temp
    let weather = res.data.result.today.weather
    this.setData({
      nowTemp: temp,
      nowWeather: weather
    })

    var imageName = ''
    let endIndex = weather.indexOf('转')
    if (endIndex >= 0) {
      imageName = weather.substring(0, endIndex)
    } else {
      imageName = weather
    }

    this.setData({
      weatherImage: weatherMap[imageName]
    })



  },
  /**
   * 解析获得穿衣、锻炼、洗车和出行指数
   */ 
  getIndex(res) {
    let dress = res.data.result.today.dressing_index
    let exercise = res.data.result.today.exercise_index
    let wash = res.data.result.today.wash_index
    let travel = res.data.result.today.travel_index
    this.setData({
      dressIndex: dress,
      exerciseIndex: exercise,
      washIndex: wash,
      travelIndex: travel
    })
  },
  /**
   * 解析获得当天天气数据
   */
  getToday(res) {
    let date = res.data.result.today.date_y
    let tempScpe = res.data.result.today.temperature
    this.setData({
      todayDate: date,
      todayTempScop: tempScpe
    })
  },
  /**
   * 生命周期函数--监听页面下拉刷新
   * 文档位置：https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page.html#%E9%A1%B5%E9%9D%A2%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0
   */
  onPullDownRefresh: function () {
    // 将停止下拉刷新的代码装入回调函数（闭包）
    // 以getWeatherData的参数形式实际传递给了wx.request的complete回调函数调用
    this.getWeatherData(() => {
      wx.stopPullDownRefresh()
    })
  },
  /**
   * 点击底部今日天气后调用
   */
  onTapDayWeather() {
    wx.navigateTo({
      url: '/pages/future/future?city=' + this.data.location + '&futureData=' + this.data.futureData
    })
  },
  /**
   * 点击定位按钮后调用
   */
  onTapLocation() {
    if (this.data.locationAuthType === UNAUTHORIZED) { //未授权
      wx.openSetting({
        success: res => {
          let auth = res.authSetting['scope.userLocation']
          if (auth) {
            this.getLocation()
          }
        }
      })
    } else {
      this.getLocation()
    }

    
  },
  /**
   * 位置定位->解析出城市
   */
  getLocation() {

    wx.getLocation({
      type: 'wgs84',
      success: res => {
        this.setData({
          locationAuthType: AUTHORIZED
        })
        this.qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res => {
            let city = res.result.address_component.city
            console.log(city);
            let _this = this
            _this.setData({
              location: city
            })
            this.getWeatherData()
          }
        })
      },
      fail: () => {
        this.setData({
          locationAuthType: UNAUTHORIZED
        })
      }
    })
  },
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按钮
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认
  confirm: function () {
    console.log("city：" + this.data.cityName )
    var _this = this;
    if(this.data.cityName != ''){
      _this.setData({
        
        hiddenmodalput: true
      })
      app.globalData.city = this.data.cityName
      this.getWeatherData()
    }
    _this.setData({
      hiddenmodalput: true
    })
    
  },
  cityNameInput: function (e) {
    this.setData({
      cityName: e.detail.value
    })
  }
    
    
  
})